package com.youdianda.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youdianda.constant.MessageConstant;
import com.youdianda.dto.MemberManagementAddDTO;
import com.youdianda.dto.MemberManagementPageDTO;
import com.youdianda.dto.MemberManagementUpDTO;
import com.youdianda.entity.SysUser;
import com.youdianda.exception.AccountLockedException;

import com.youdianda.mapper.SysRoleMapper;
import com.youdianda.mapper.SysUserMapper;


import com.youdianda.result.Result;
import com.youdianda.service.ISysRoleService;
import com.youdianda.service.ISysUserService;
import com.youdianda.vo.MemberManagementPageQueryVO;
import com.youdianda.vo.MemberManagementpageVo;
import com.youdianda.vo.MemberManagementqueVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author mosen
 * @since 2023-05-15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private SysRoleMapper sysRoleMapper;


    /*
    用户详情
    * */
    @Override
    public Result<MemberManagementqueVo> getMerById(String id) {

        //1.非空判断
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.查找数据
        SysUser sysUser = sysUserMapper.selectById(id);
        //封装数据
        MemberManagementqueVo memberManagementqueVo = new MemberManagementqueVo();
        BeanUtils.copyProperties(sysUser, memberManagementqueVo);

        memberManagementqueVo.setLogin_name(sysUser.getLoginName());
        memberManagementqueVo.setLogin_ip(sysUser.getLoginIp());
        memberManagementqueVo.setLogin_date(sysUser.getLoginDate());
        memberManagementqueVo.setCreate_date(sysUser.getCreateDate());
        memberManagementqueVo.setUpdate_date(sysUser.getUpdateDate());
        memberManagementqueVo.setDel_flag(sysUser.getDelFlag());
        memberManagementqueVo.setDefault_data(sysUser.getDefaultData());

        String str = sysUser.getRoleId();
        StringBuffer stringBuffer = new StringBuffer("");
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i)!='[' && str.charAt(i)!=']' && str.charAt(i)!='"'){
                stringBuffer.append(str.charAt(i));
            }
        }

        List<String> stringList = Arrays.asList(stringBuffer.toString().split(",",-1));
        memberManagementqueVo.setRole_id(stringList);
        memberManagementqueVo.setPassword("")   ;

        return Result.success(memberManagementqueVo);
    }

    /*
     * 分页查询
     * */
    @Override
    public Result<MemberManagementpageVo> page(MemberManagementPageDTO dto) {
        //非空判断
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getLimit() == null) {
            dto.setLimit(10);
        }
        //业务判断
        String mobile = dto.getPhone();
        String username = dto.getLogin_name();
        String status = dto.getStatus();

        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();

        if (mobile != null) {
            lqw.like(SysUser::getPhone, mobile);
        }
        if (username != null) {
            lqw.like(SysUser::getLoginName, username);
        }
        if (status != null) {
            sysUserMapper.selectList(lqw);
        }

        //开始分页
        IPage<SysUser> page = new Page<>(dto.getPage(), dto.getLimit());
        //分页查询
        IPage<SysUser> sysUserIPage = sysUserMapper.selectPage(page, lqw);
        //改造数据结果
        List<MemberManagementPageQueryVO> voList = new ArrayList<>();
        List<SysUser> records = sysUserIPage.getRecords();
        for (SysUser record : records) {
            MemberManagementPageQueryVO vo = new MemberManagementPageQueryVO();
            BeanUtils.copyProperties(record,vo);
            vo.setCreate_date(record.getCreateDate());
            vo.setUpdate_date(record.getUpdateDate());
            vo.setDefault_data(record.getDefaultData());
            vo.setDel_flag(record.getDelFlag());
            vo.setLogin_name(record.getLoginName());
            vo.setLogin_ip(record.getLoginIp());
            vo.setLogin_date(record.getLoginDate());

            String roleIdStr = sysUserMapper.getRoleIdById(record.getId());
            //处理角色id字符串,变成字符串集合,删除[]和"
            StringBuffer stringBuffer = new StringBuffer("");
            for (int i = 0; i < roleIdStr.length(); i++) {
                if (roleIdStr.charAt(i)!='[' && roleIdStr.charAt(i)!=']' && roleIdStr.charAt(i)!='"'){
                    stringBuffer.append(roleIdStr.charAt(i));
                }
            }

            List<String> roleList = Arrays.asList(stringBuffer.toString().split(",", -1));

            vo.setRole_id(roleList);

            //vo的roleName属性,根据roleId找role的name属性封装字符串集合
            List<String> roleName = new ArrayList<>();

            for (String roleId : roleList) {
                String name = sysRoleMapper.getRoleNameById(roleId);
                roleName.add(name);
            }

            vo.setRolename(roleName);

            voList.add(vo);


        }

        //封装数据
        MemberManagementpageVo vo = MemberManagementpageVo.builder()
                .currentPage(page.getCurrent())
                .pageSize(page.getSize())

                .totalPages(sysUserIPage.getPages())
                .count(sysUserIPage.getTotal())
                //TODO 改造data数据
                .data(voList)
                .build();
        return Result.success(vo);
    }


    @Override
    public void add(MemberManagementAddDTO memberManagementAddDTO) {
        if (memberManagementAddDTO.getLogin_name() == null) {
            throw new AccountLockedException(MessageConstant.ID_NOT_FOUND);
        }

        //封装数据
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(memberManagementAddDTO, sysUser);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(memberManagementAddDTO.getPassword().getBytes(StandardCharsets.UTF_8)));
        List<String> roleIdList = memberManagementAddDTO.getRole_id();
        StringBuffer stringBuffer = new StringBuffer("");
        stringBuffer.append("[");
        for (int i = 0; i < roleIdList.size(); i++) {
            if (i==roleIdList.size()-1){
                stringBuffer.append('"');
                stringBuffer.append(roleIdList.get(i));
                stringBuffer.append('"');
            }else{
                stringBuffer.append('"');
                stringBuffer.append(roleIdList.get(i));
                stringBuffer.append('"');
                stringBuffer.append(",");
            }
        }
        stringBuffer.append("]");

        sysUser.setRoleId(stringBuffer.toString());
        sysUser.setLoginName(memberManagementAddDTO.getLogin_name());
        sysUser.setCreateDate(LocalDateTime.now());
        sysUser.setDefaultData("1");
        sysUser.setDelFlag("0");
        sysUser.setUpdateDate(LocalDateTime.now());
        sysUser.setId(UUID.randomUUID().toString());

        //新增对象
        sysUserMapper.insert(sysUser);


    }
    /*
    删除
    * */
    @Override
    public Result del(String id) {
        //非空判断
        if (id == null) {
            Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //执行删除操作
        sysUserMapper.deleteById(id);
        return Result.success();
    }

    /*
     * 修改*/
    @Override
    public Result updata(MemberManagementUpDTO memberManagementUpDTO) {
        //非空判断
        if (memberManagementUpDTO == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //封装数据
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(memberManagementUpDTO, sysUser);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(memberManagementUpDTO.getPassword().getBytes(StandardCharsets.UTF_8)));

        sysUser.setLoginName(memberManagementUpDTO.getLogin_name());

        List<String> roleList = memberManagementUpDTO.getRole_id();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        for (int i = 0; i < roleList.size(); i++) {
            if (i==roleList.size()-1){
                stringBuffer.append('"');
                stringBuffer.append(roleList.get(i));
                stringBuffer.append('"');
            }else{
                stringBuffer.append('"');
                stringBuffer.append(roleList.get(i));
                stringBuffer.append('"');
                stringBuffer.append(",");
            }
        }
        stringBuffer.append("]");

        sysUser.setRoleId(stringBuffer.toString());


        //执行修改操作
        sysUserMapper.updateUserById(sysUser);

        return Result.success();
    }


}
